import axios from "axios";

const instance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  // 生产环境
  // https://yourdomain.com/api
  // 开发环境
  // http://localhost:3000/api
  timeout: 5000,
  headers: { "X-Custom-Hearder": "foobar" },
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    return response;
  },
  async (error) => {
    const { config, response } = error;
    if (response && response.status === 401) {
      // 获取refreshToken，这里假设从本地存储获取，同样可按实际调整
      const refreshToken = localStorage.getItem("refreshToken");
      if (refreshToken) {
        try {
          // 发送请求使用refreshToken获取新的token，这里的接口地址需替换为实际的后端提供的刷新token接口
          const { data } = await axios.post("/api/refresh-token", {
            refreshToken,
          });
          const newToken = data.token;
          const newRefreshToken = data.refreshToken;
          // 存储新的token和refreshToken到本地存储
          localStorage.setItem("token", newToken);
          localStorage.setItem("refreshToken", newRefreshToken);
          // 更新当前请求的请求头中的token
          config.headers.Authorization = `Bearer ${newToken}`;
          // 重新发起请求
          return instance(config);
        } catch (refreshError) {
          // 如果刷新token也失败了，可能需要跳转到登录页等处理逻辑，这里可按实际需求完善
          console.log("刷新token失败", refreshError);
          return Promise.reject(refreshError);
        }
      }
    }

    return Promise.reject(error);
  }
);

export default instance;
